package com.chushouya.order.service.api.impl;

import com.chushouya.order.constants.AlipayOrderChangedStatusEnum;
import com.chushouya.order.constants.OrderActionLogEnum;
import com.chushouya.order.constants.OrderStatusEnum;
import com.chushouya.order.dao.entity.OrderEntity;
import com.chushouya.order.dao.repository.OrderRepository;
import com.chushouya.order.dto.admin.miniorder.AlipayOpenMiniOrderChangedDTO;
import com.chushouya.order.service.api.AlipayOpenMiniOrderChangedService;
import com.chushouya.order.service.common.OrderLogService;
import com.general.framework.core.lang.Jsons;
import com.general.framework.core.lang.Strings;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;

@Service
public class AlipayOpenMiniOrderChangedServiceImpl implements AlipayOpenMiniOrderChangedService {


    @Resource
    private OrderRepository orderRepository;

    @Resource
    private OrderLogService orderLogService;

    /**
     * 获取订单信息
     * @param orderNo
     */
    private OrderEntity getOrder(String orderNo) {
        OrderEntity orderEntity = orderRepository.selectByOrderNo(orderNo);
        if (Objects.isNull(orderEntity)) {
            throw new RuntimeException("订单不存在");
        }
        return orderEntity;
    }

    @Override
    public void alipayOpenMiniOrderChanged(Map data) {
        final AlipayOpenMiniOrderChangedDTO alipayOpenMiniOrderChangedDTO = Jsons.parseObject(data.get("biz_content").toString(),AlipayOpenMiniOrderChangedDTO.class);
        final String status = alipayOpenMiniOrderChangedDTO.getStatus();
        final String outOrderId = alipayOpenMiniOrderChangedDTO.getOutOrderId();

        OrderEntity orderEntity = getOrder(outOrderId);
        final Long orderId = orderEntity.getOrderId();
        final String msg = Strings.format("支付宝小程序订单状态变更,订单状态:{}", AlipayOrderChangedStatusEnum.getDesc(status));
        orderLogService.addOrderActionLog(orderId,  OrderActionLogEnum.FOLLOW_ORDER.value(), msg);
        if(Objects.equals(orderEntity.getOrderStatus(), OrderStatusEnum.COMPLETE.value())){
            return;
        }
        if (Objects.equals(AlipayOrderChangedStatusEnum.FINISHED.value(),status)) {
            //todo 完成订单
//            commonOrderActionService.completeOrder(orderEntity, OrderPayTypeEnum.ALIPAY.value(),orderEntity.getCompletePrice(),Strings.format("用户确认回收价格 成交价格：{}元",orderEntity.getCompletePrice()), OrderStatusEnum.COMPLETE.value());
        } else if (Objects.equals(AlipayOrderChangedStatusEnum.CANCEL_CLOSED.value(),status)) {
            //todo 取消订单
//            commonOrderActionService.closeOrder(orderEntity, "支付宝用户客户端取消订单", OrderStatusEnum.CANCELLED.value());
        }
    }
}
